import sys, os, random
from PyQt5.QtCore import Qt, QSize, QUrl, QTimer, QTime
from PyQt5.QtGui import QFont, QIcon, QPalette, QColor
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QHBoxLayout, QVBoxLayout, QSplitter,
                             QLabel, QPushButton, QSlider, QTreeWidget, QTreeWidgetItem, QListWidget,
                             QListWidgetItem, QAbstractItemView, QStyle, QFileDialog, QScrollArea)
from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent
from PyQt5.QtMultimediaWidgets import QVideoWidget
from EnhancedWidget import EnhancedPlaylist
        
class MusicPlayer(QMediaPlayer):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.playlist = []
        self.play_history = []
        self.current_index = -1
        self.play_modes = ['sequential', 'random', 'single']
        self.current_mode = 0
        self.volume_level = 50
        self.setVolume(self.volume_level)
        
        #self.positionChanged.connect(self.update_position)
        #self.durationChanged.connect(self.update_duration)
        #self.stateChanged.connect(self.handle_state_change)

    def add_to_playlist(self, file_path):
        if os.path.isfile(file_path):
            self.playlist.append(file_path)
            if self.current_index == -1:
                self.current_index = 0

    def play_next(self) -> int:
        if len(self.playlist) == 0:
            return
        
        if self.current_mode == 0:  # Sequential
            self.current_index = (self.current_index + 1) % len(self.playlist)
        elif self.current_mode == 1:  # Random
            self.current_index = random.randint(0, len(self.playlist)-1)
        elif self.current_mode == 2:  # Single
            pass
        
        self.load_current()
        
        return self.current_index

    def play_previous(self) -> int:
        if len(self.playlist) == 0:
            return -1
        
        self.current_index = (self.current_index - 1) % len(self.playlist)
        self.load_current()
        
        return self.current_index

    def load_current(self):
        if 0 <= self.current_index < len(self.playlist):
            media = QMediaContent(QUrl.fromLocalFile(self.playlist[self.current_index]))
            self.setMedia(media)
            self.play()
            #self.play_history.append(self.playlist[self.current_index])

    def update_position(self, position):
        pass  # 将在主界面更新进度条

    def update_duration(self, duration):
        """处理持续时间变化事件"""
        if duration > 0:
            # 转换为秒并保留两位小数
            self.total_duration = duration / 1000  
            # 发送信号给主界面更新显示
            self.durationChanged.emit(duration)  
        pass  # 更新持续时间显示

    def handle_state_change(self, state):
        pass  # 更新播放按钮状态
    
    def handle_media_status(self, status) -> int:
        """处理媒体状态变化"""
        if status == QMediaPlayer.EndOfMedia:
            # 根据播放模式处理
            if self.current_mode == 2:  # 单曲循环
                self.setPosition(0)
                self.play()
            else:
                self.play_next()
        
        return self.current_index
                

class FluentMusicPlayer(QMainWindow):
    def __init__(self):
        super().__init__()
        self.player = MusicPlayer()
        self._playlist_file_path = "D:\迅雷云盘"
        self.initUI()
        self.initStyle()
        self.initIcon()
        self.init_connections()
        #加载播放列表
        self.load_playlist()
        # 添加节流处理，防止频繁更新
        self.update_timer = QTimer()
        self.update_timer.setInterval(200)  # 200ms更新间隔
        self.update_timer.timeout.connect(self.throttled_update)
        self.update_timer.start()
    
    def load_playlist(self):
        for root, dirs, files in os.walk(self._playlist_file_path):
            for file in files:
                if file.endswith('.mp3'):
                    #print(os.path.join(root, file))
                    self.player.add_to_playlist(os.path.join(root, file))
                    item = QListWidgetItem(file[:file.rfind('.')])
                    self.playlist.addItem(item)

    def initUI(self):
        # 窗口基础设置
        self.setWindowTitle("Fluent Music")
        self.setGeometry(100, 100, 1200, 800)
        self.setMinimumSize(800, 600)

        # 主布局容器
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        main_layout = QVBoxLayout(main_widget)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)

        # 标题栏
        title_bar = self.createTitleBar()
        main_layout.addWidget(title_bar)

        # 主内容区
        content_splitter = QSplitter()
        main_layout.addWidget(content_splitter)

        # 左侧播放列表
        left_panel = self.createLeftPanel()
        content_splitter.addWidget(left_panel)

        # 右侧封面区
        right_panel = self.createRightPanel()
        content_splitter.addWidget(right_panel)

        # 底部控制栏
        control_bar = self.createControlBar()
        main_layout.addWidget(control_bar)

    def createTitleBar(self):
        title_bar = QWidget()
        title_bar.setFixedHeight(60)
        title_bar.setObjectName("titleBar")
        layout = QHBoxLayout(title_bar)
        layout.setContentsMargins(12, 0, 12, 0)

        # 左侧Logo
        logo = QLabel("🎵 Fluent Music")
        logo.setFont(QFont("Segoe UI", 14))
        layout.addWidget(logo, alignment=Qt.AlignLeft)
        
        # 添加文件打开按钮
        self.open_btn = QPushButton("Open Files")
        layout.addWidget(self.open_btn, alignment=Qt.AlignLeft)

        # 右侧控制按钮
        btn_group = QWidget()
        btn_layout = QHBoxLayout(btn_group)
        btn_layout.setSpacing(8)

        self.theme_btn = QPushButton()
        self.theme_btn.setIcon(QIcon("assets/theme.svg"))
        self.theme_btn.setFixedSize(32, 32)
        btn_layout.addWidget(self.theme_btn)

        buttons = ["min", "max", "close"]
        for btn in buttons:
            button = QPushButton()
            button.setFixedSize(32, 32)
            button.setObjectName(btn+"Button")
            btn_layout.addWidget(button)

        layout.addWidget(btn_group, alignment=Qt.AlignRight)
        return title_bar

    def createLeftPanel(self):
        panel = QWidget()
        panel.setMinimumWidth(300)
        layout = QVBoxLayout(panel)

        # 树状歌单
        tree = QTreeWidget()
        tree.setHeaderHidden(True)
        tree.setIndentation(12)
        playlists = ["我的收藏", "最近播放", "创建的歌单"]
        for pl in playlists:
            item = QTreeWidgetItem([pl])
            tree.addTopLevelItem(item)
        layout.addWidget(tree)

        # 当前播放列表
        self.playlist = EnhancedPlaylist()
        #self.playlist.setAlternatingRowColors(True)
        self.playlist.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel)
        
        layout.addWidget(self.playlist)
        return panel

    def createRightPanel(self):
        panel = QWidget()
        layout = QVBoxLayout(panel)
        layout.setAlignment(Qt.AlignCenter)

        # 专辑封面
        #self.cover = QLabel()
        #self.cover.setFixedSize(200, 200)
        #self.cover.setStyleSheet("""
        #    background: #E0E0E0;
        #    border-radius: 100px;
        #    border: 2px solid #FFFFFF;
        #""")
        #layout.addWidget(self.cover)
        
        self.lyrics_container = QScrollArea()
        self.lyrics_container.setWidgetResizable(True)
        self.lyrics_content = QWidget()
        self.lyrics_layout = QVBoxLayout(self.lyrics_content)
        self.lyrics_layout.setAlignment(Qt.AlignCenter)
        
        self.lyrics_labels = []
        self.current_lyric_index = -1
        
        self.lyrics_container.setWidget(self.lyrics_content)
        layout.addWidget(self.lyrics_container)

        # 歌曲信息
        #self.song_info = QLabel("No Song Playing")
        #self.song_info.setFont(QFont("Segoe UI", 14))
        #layout.addWidget(self.song_info, alignment=Qt.AlignCenter)
        return panel

    def createControlBar(self):
        panel = QWidget()
        panel.setFixedHeight(150)
        layout = QVBoxLayout(panel)

        # 进度条
        process_layout = QHBoxLayout()
        
        # 在底部控制栏添加时间显示
        self.time_label = QLabel("00:00 / 00:00")
        #self.time_label.setAlignment(Qt.AlignCenter)
        process_layout.addWidget(self.time_label)
        
        self.progress = QSlider(Qt.Horizontal)
        self.progress.setRange(0, 100)
        process_layout.addWidget(self.progress)
        layout.addLayout(process_layout)

        # 控制按钮组
        control_layout = QHBoxLayout()

        # 左侧控制组
        left_controls = QVBoxLayout()
        self.play_mode = QPushButton("顺序播放")
        self.play_mode.setToolTip("播放模式：顺序/随机/单曲")
        left_controls.addWidget(self.play_mode)
        control_layout.addLayout(left_controls)

        # 中间控制组
        center_controls = QHBoxLayout()
        btn_size = QSize(48, 48)
        self.prev_btn = QPushButton()
        self.play_btn = QPushButton()
        self.play_btn.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.next_btn = QPushButton()
        for btn in [self.prev_btn, self.play_btn, self.next_btn]:
            btn.setFixedSize(btn_size)
            center_controls.addWidget(btn)
        control_layout.addStretch()  # Add stretch before center controls
        control_layout.addLayout(center_controls)
        control_layout.addStretch()  # Add stretch after center controls

        # 右侧控制组(音量）
        right_controls = QHBoxLayout()
        right_controls.setSpacing(8)
        
        self.volume_icon = QLabel()
        self.volume_icon.setPixmap(self.style().standardIcon(QStyle.SP_MediaVolume).pixmap(24,24))
        
        self.volume = QSlider(Qt.Horizontal)
        self.volume.setRange(0, 100)
        self.volume.setValue(50)
        self.volume.setFixedWidth(120)
        
        self.volume_label = QLabel("50%")
        self.volume_label.setFixedWidth(40)
        
        right_controls.addStretch()
        right_controls.addWidget(self.volume_icon)
        right_controls.addWidget(self.volume)
        right_controls.addWidget(self.volume_label)
        right_controls.addStretch()
        
        control_layout.addLayout(right_controls)

        layout.addLayout(control_layout)
        return panel

    def initStyle(self):
        self.setStyleSheet("""
            QWidget {
                font-family: 'Segoe UI';
                background: #FFFFFF;
            }
            #titleBar {
                background: #F3F3F3;
                border-bottom: 1px solid #E0E0E0;
            }
            QPushButton {
                border: none;
                border-radius: 4px;
                padding: 4px;
            }
            QPushButton:hover {
                background: #E0E0E0;
            }
            QSlider::groove:horizontal {
                height: 4px;
                background: #E0E0E0;
                border-radius: 2px;
            }
            QSlider::handle:horizontal {
                width: 12px;
                margin: -4px 0;
                background: #0078D4;
                border-radius: 6px;
            }
            QListWidget::item:hover {
                background: rgba(0,0,0,0.05);
                transform: translateX(4px);
            }
            QListWidget::item:selected {
                background: #0078D4;
                color: #FFFFFF;
            }
        """)

    def initIcon(self):
        self.play_btn.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.prev_btn.setIcon(self.style().standardIcon(QStyle.SP_MediaSeekBackward))
        self.next_btn.setIcon(self.style().standardIcon(QStyle.SP_MediaSeekForward))
    
    def init_connections(self):
        # 连接播放器信号
        self.player.positionChanged.connect(self.update_lyrics)
        self.player.durationChanged.connect(self.update_duration_display)
        #self.player.stateChanged.connect(self.update_play_button)
        self.player.mediaStatusChanged.connect(self.handle_media_status)

        # 连接按钮事件
        self.play_btn.clicked.connect(self.toggle_play)
        self.prev_btn.clicked.connect(self.play_previous)
        self.next_btn.clicked.connect(self.play_next)
        self.volume.valueChanged.connect(self.set_volume)
        #self.progress.sliderMoved.connect(self.set_position)
        self.open_btn.clicked.connect(self.open_files)
        self.playlist.itemDoubleClicked.connect(self.play_selected)
    
    def toggle_play(self):
        if self.player.state() == QMediaPlayer.PlayingState:
            self.player.pause()
        else:
            if self.player.mediaStatus() == QMediaPlayer.NoMedia:
                if len(self.player.playlist) > 0:
                    self.player.load_current()
                    self.load_lyrics(self.player.current_index)
    
    def play_previous(self):
        prev_index = self.player.play_previous()
        if prev_index != -1:
            self.playlist.setCurrentRow(prev_index)
            self.load_lyrics(prev_index)
    
    def play_next(self):
        next_index = self.player.play_next()
        if next_index != -1:
            #self.highlight_current_song(self.playlist.item(next_index))
            self.playlist.setCurrentRow(next_index)
            self.load_lyrics(next_index)

    def set_volume(self, value):
        self.player.setVolume(value)
        self.volume.setValue(value)
        self.volume_label.setText(f"{value}%")

    def open_files(self):
        files, _ = QFileDialog.getOpenFileNames(self,
            "选择音乐文件", "",
            "音频文件 (*.mp3 *.wav *.ogg *.flac)")
        
        for file in files:
            self.player.add_to_playlist(file)
            filename = os.path.basename(file)
            item = QListWidgetItem(filename)
            item.setData(Qt.UserRole, file)
            self.playlist.addItem(item)
    
    def play_selected(self, item):
        # Highlight the selected song
        item.setSelected(True)
        # Update the player's current index and load the selected song
        self.player.current_index = self.playlist.row(item)
        self.player.load_current()
        self.load_lyrics(self.player.current_index)
    
    def update_duration_display(self, duration):
        """更新界面持续时间显示"""
        #print(f"Duration: {duration}")
        if duration > 0:
            # 设置进度条最大范围
            self.progress.setMaximum(duration)
            
            # 格式化时间显示
            total_seconds = duration // 1000
            minutes = total_seconds // 60
            seconds = total_seconds % 60
            self.total_time = f"{minutes:02d}:{seconds:02d}"
            
            # 更新标签显示
            current_text = self.time_label.text().split(" / ")[0]
            self.time_label.setText(f"{current_text} / {self.total_time}")

        else:  # 处理无效持续时间
            self.time_label.setText("00:00 / 00:00")
            self.progress.setMaximum(0)
    
    def handle_media_status(self, status):
        next_index = self.player.handle_media_status(status)
        if next_index != -1:
            self.playlist.setCurrentRow(next_index)
            self.load_lyrics(next_index)
    def update_progress(self, position):
        """更新播放进度"""
        if position > 0 and self.player.duration() > 0:
            # 当前时间计算
            current_seconds = position // 1000
            minutes = current_seconds // 60
            seconds = current_seconds % 60
            
            # 组合完整时间显示
            current_time = f"{minutes:02d}:{seconds:02d}"
            total_time = self.total_time if hasattr(self, 'total_time') else "00:00"
            
            # 更新标签和进度条
            self.time_label.setText(f"{current_time} / {total_time}")
            self.progress.setValue(position)
    
    def throttled_update(self):
        if self.player.state() == QMediaPlayer.PlayingState:
            self.update_progress(self.player.position())
    
    # 新增高亮显示方法，没有使用该方法
    def highlight_current_song(self, current_item):
        # 清除所有高亮样式
        for i in range(self.playlist.count()):
            item = self.playlist.item(i)
            item.setBackground(QColor(0, 0, 0, 0))  # 透明背景
            item.setForeground(QColor(0, 0, 0))     # 默认文字颜色

        # 设置当前项目高亮
        current_item.setBackground(QColor("#0078D4"))  # 主色背景
        current_item.setForeground(QColor("#FFFFFF"))  # 白色文字
        self.playlist.scrollToItem(current_item, QAbstractItemView.PositionAtCenter)  # 滚动到视图中心
        self.playlist.setCurrentItem(current_item)
    
    def load_lyrics(self, current_item_index):
        """加载歌词文件"""
        
        #获取歌词文件路径
        item = self.playlist.item(current_item_index)
        displayed_text = item.text()
        file_path = os.path.join(self._playlist_file_path, f"{displayed_text}.lrc")
        
        # 清空现有歌词
        for label in self.lyrics_labels:
            label[1].deleteLater()
        self.lyrics_labels = []
        self.current_lyric_index = -1
        
        # 解析LRC文件
        lyrics = self.parse_lrc(file_path)
        for time_stamp, text in lyrics:
            label = QLabel(text)
            label.setFont(QFont("Segoe UI", 12))
            label.setStyleSheet("color: #666666; padding: 4px;")
            label.setAlignment(Qt.AlignCenter)
            self.lyrics_labels.append((time_stamp, label))
            self.lyrics_layout.addWidget(label)
        
        # 按时间排序
        self.lyrics_labels.sort(key=lambda x: x[0])

    def parse_lrc(self, path):
        """解析LRC歌词文件"""
        lyrics = []
        try:
            with open(path, 'r', encoding='utf-8') as f:
                for line in f:
                    if line.startswith('['):
                        time_part = line[1:line.index(']')]
                        text = line[line.index(']')+1:].strip()
                        if ':' in time_part:
                            m, s = time_part.split(':')
                            time = int(m)*60*1000 + float(s)*1000
                            lyrics.append((time, text))
        except:
            return [(0, "暂无歌词")]
        return lyrics
    
    def update_lyrics(self, position):
        """更新当前歌词"""
        print(f"Position: {position}")
        new_index = -1
        for i, (time, label) in enumerate(self.lyrics_labels):
            if time <= position:
                new_index = i
            else:
                break
        
        if new_index != self.current_lyric_index:
            # 清除旧高亮
            if self.current_lyric_index != -1:
                self.lyrics_labels[self.current_lyric_index][1].setStyleSheet("color: #666666;")
            
            # 设置新高亮
            if new_index != -1:
                label = self.lyrics_labels[new_index][1]
                label.setFont(QFont("Segoe UI", 14))
                label.setStyleSheet("""
                    color: #0078D4;
                    padding: 4px;
                """)
                '''
                    font-size: 14px;
                    font-weight: 500;
                '''
                # 滚动到可见区域
                self.lyrics_container.ensureWidgetVisible(label)
            
            self.current_lyric_index = new_index

if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setStyle("Fusion")
    player = FluentMusicPlayer()
    player.show()
    sys.exit(app.exec_())